package com.example.demo.Service.Impl;

import com.example.demo.Service.EmailService;
import com.example.demo.Vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.Random;

@Service
public class EmailServiceImpl implements EmailService {
    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String from;

    @Override
    public boolean sendMimeMail(String email, HttpSession session) {
        try {
            System.out.println(session.getId());
            SimpleMailMessage mailMessage = new SimpleMailMessage();

            mailMessage.setSubject("验证码邮件");//主题
            //生成随机数
            String code = randomCode();

            //将随机数放置到session中
            session.setAttribute("email", email);
            session.setAttribute("code", code);

            mailMessage.setText("您收到的验证码是：" + code);//内容

            mailMessage.setTo(email);//发给谁

            mailMessage.setFrom(from);//你自己的邮箱

            mailSender.send(mailMessage);//发送
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }

    private String randomCode() {
        StringBuilder str = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            str.append(random.nextInt(10));
        }
        return str.toString();

    }

    @Override
    public boolean compareVerificationCode(String voCode, String voEmail, HttpSession session) {
        String email = (String) session.getAttribute("email");
        String code = (String) session.getAttribute("code");
        System.out.println(session.getId());
        //如果email数据为空，或者不一致，注册失败
        if (email == null || email.isEmpty() || !email.equals(voEmail)) {
            System.out.println(email+"   "+voEmail);
            System.out.println(code+"   "+voCode);
            return false;
        } else if (!code.equals(voCode)) {
            System.out.println(code+"   "+voCode);
            //return "error,请重新注册";
            return false;
        }
        //跳转成功页面
        return true;

    }

}
